package com.example.business.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.business.demo.constant.DemoConstant;
import com.example.business.demo.convert.DemoConvert;
import com.example.business.demo.dto.DemoDTO;
import com.example.business.demo.entity.DemoEntity;
import com.example.business.demo.mapper.DemoMapper;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Demo服务类
 */
@Service
public class DemoService {
    
    @Autowired
    private DemoMapper demoMapper;
    
    /**
     * 分页查询有效的Demo数据
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 分页结果
     */
    public Page<DemoDTO> queryActiveDemos(Integer pageNum, Integer pageSize) {
        // 创建分页对象
        Page<DemoEntity> page = new Page<DemoEntity>(
            pageNum == null ? DemoConstant.DEFAULT_PAGE_NUM : pageNum,
            pageSize == null ? DemoConstant.DEFAULT_PAGE_SIZE : pageSize
        );
        
        // 构建查询条件
        LambdaQueryWrapper<DemoEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DemoEntity::getStatus, DemoConstant.STATUS_VALID)
                   .orderByDesc(DemoEntity::getCreateTime);
        
        // 执行查询
        Page<DemoEntity> entityPage = demoMapper.selectPage(page, queryWrapper);
        
        // 转换为DTO
        List<DemoDTO> dtoList = entityPage.getRecords().stream()
                .map(DemoConvert::toDTO)
                .collect(Collectors.toList());
        
        // 构建返回结果
        Page<DemoDTO> dtoPage = new Page<>();
        dtoPage.setRecords(dtoList);
        dtoPage.setTotal(entityPage.getTotal());
        dtoPage.setCurrent(entityPage.getCurrent());
        dtoPage.setSize(entityPage.getSize());
        
        return dtoPage;
    }

        
    private DemoDTO convertToDTO(DemoEntity entity) {
        DemoDTO dto = new DemoDTO();
        BeanUtils.copyProperties(entity, dto);
        return dto;
    }
}